﻿using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;
using HRProject.Code.DAO;
using HRProject.Code.Common;
using HRProject.Code.DTO;
using System.Collections.Generic;
using System.Globalization;

namespace HRProject.Task
{
    public partial class EditTask : System.Web.UI.Page
    {
        private Guid taskId;

        protected void Page_Load(object sender, EventArgs e)
        {
            try
            {
                taskId = new Guid(Request.Params["taskId"]);
            }
            catch (Exception exp)
            {
                Console.Out.WriteLine(exp.Message);
                Util.CloseDialog(Response);
                return;
            }

            if (!IsPostBack)
            {
                TaskDAO taskDAO = new TaskDAO();
                BLTaskFilter taskFilter = new BLTaskFilter();
                taskFilter.Id = taskId;
                taskFilter.Name = string.Empty;
                taskFilter.Type = new BLTaskType();
                taskFilter.Type.Id = Guid.Empty;
                List<BLTask> tasks = taskDAO.search(taskFilter);

                if (tasks.Count > 0)
                {
                    tbxName.Text = tasks[0].Name;
                    hdfInChargeUserId.Value = tasks[0].InChargeUserId.ToString();

                    TaskTypeDAO taskTypeDAO = new TaskTypeDAO();
                    BLTaskType filter = new BLTaskType();
                    filter.Id = Guid.Empty;
                    filter.Name = string.Empty;
                    filter.Parent = new BLTaskType();
                    filter.Parent.Id = Guid.Empty;
                    List<BLTaskType> taskTypes = taskTypeDAO.search(filter);
                    ddlTaskType.DataSource = taskTypes;
                    ddlTaskType.DataValueField = "Id";
                    ddlTaskType.DataTextField = "Name";
                    ddlTaskType.DataBind();
                    ddlTaskType.SelectedValue = tasks[0].Type.Id.ToString();

                    if (!Constant.DefaultMinDate.Equals(tasks[0].EstimateStartDate))
                        tbxEstimateStartDate.Text = tasks[0].EstimateStartDate.ToString("dd/MM/yyyy HH:ss");
                    if (!Constant.DefaultMinDate.Equals(tasks[0].EstimateFinishDate))
                        tbxEstimateFinishDate.Text = tasks[0].EstimateFinishDate.ToString("dd/MM/yyyy HH:ss");
                    if (!Constant.DefaultMinDate.Equals(tasks[0].RealStartDate))
                        tbxRealStartDate.Text = tasks[0].RealStartDate.ToString("dd/MM/yyyy HH:ss");
                    if (!Constant.DefaultMinDate.Equals(tasks[0].RealFinishDate))
                        tbxRealFinishDate.Text = tasks[0].RealFinishDate.ToString("dd/MM/yyyy HH:ss");

                    DepartmentDAO departmentDao = new DepartmentDAO();
                    BLDepartment deptFilter = new BLDepartment();
                    deptFilter.Id = Guid.Empty;
                    deptFilter.Name = string.Empty;
                    deptFilter.Parent = new BLDepartment();
                    deptFilter.Parent.Id = Guid.Empty;
                    List<BLDepartment> depts = departmentDao.search(deptFilter);
                    depts.Insert(0, deptFilter);
                    ddlDepartment.DataSource = depts;
                    ddlDepartment.DataBind();
                    try
                    {
                        lblInChargeAgent.Text = Membership.GetUser(tasks[0].InChargeUserId).UserName;
                    }
                    catch (Exception exp)
                    {
                        Console.Out.WriteLine(exp.Message);
                    }
                    txaDescription.Text = tasks[0].Description;
                }
            } 
        }

        protected void btnOK_Click(object sender, EventArgs e)
        {
            if (!BLAuthentication.IsEditAllowed)
            {
                lblError.Text = ContentProvider.GetMessage("NotAuthorized");
                return;
            }

            TaskDAO taskDAO = new TaskDAO();
            BLTaskFilter taskFilter = new BLTaskFilter();
            taskFilter.Id = taskId;
            taskFilter.Name = string.Empty;
            taskFilter.Type = new BLTaskType();
            taskFilter.Type.Id = Guid.Empty;
            List<BLTask> tasks = taskDAO.search(taskFilter);
            if (tasks.Count < 1)
            {
                return;
            }
            BLTask task = tasks[0];

            BLTaskType type = new BLTaskType();
            task.Name = tbxName.Text.Trim();
            if (string.IsNullOrEmpty(task.Name))
            {
                lblError.Text = ContentProvider.GetMessage("MandatoryInput").Replace("{0}", ContentProvider.GetString("TaskName"));
                return;
            }

            try
            {
                type.Id = new Guid(ddlTaskType.SelectedValue);
            }
            catch (Exception exp)
            {
                type.Id = Guid.Empty;
                Console.Out.Write(exp.StackTrace);
            }
            if (type.Id.Equals(Guid.Empty))
            {
                lblError.Text = ContentProvider.GetMessage("MandatorySelection").Replace("{0}",ContentProvider.GetString("TaskType"));
                return;
            }
            task.Type = type;

            task.Description = txaDescription.Text.Trim();

            DateTime date;
            if (DateTime.TryParseExact(tbxEstimateStartDate.Text, Constant.DateTimeFormats, Constant.enCulture, DateTimeStyles.None, out date))
            {
                task.EstimateStartDate = date;
            }
            else
            {
                task.EstimateStartDate = Constant.DefaultMinDate;
            }
            if (DateTime.TryParseExact(tbxEstimateFinishDate.Text, Constant.DateTimeFormats, Constant.enCulture, DateTimeStyles.None, out date))
            {
                task.EstimateFinishDate = date;
            }
            else
            {
                task.EstimateFinishDate = Constant.DefaultMaxDate;
            }
            if (task.EstimateStartDate != null && task.EstimateFinishDate != null
                && task.EstimateFinishDate < task.EstimateStartDate)
            {
                lblError.Text = ContentProvider.GetMessage("InvalidBoundaries").Replace("{0}", ContentProvider.GetString("EstimateTime"));
                return;
            }

            if (DateTime.TryParseExact(tbxRealStartDate.Text, Constant.DateTimeFormats, Constant.enCulture, DateTimeStyles.None, out date))
            {
                task.RealStartDate = date;
            }
            else
            {
                task.RealStartDate = Constant.DefaultMinDate;
            }
            if (DateTime.TryParseExact(tbxRealFinishDate.Text, Constant.DateTimeFormats, Constant.enCulture, DateTimeStyles.None, out date))
            {
                task.RealFinishDate = date;
            }
            else
            {
                task.RealFinishDate = Constant.DefaultMaxDate;
            }
            if (task.RealStartDate != null && task.RealFinishDate != null
                && task.RealFinishDate < task.RealStartDate)
            {
                lblError.Text = ContentProvider.GetMessage("InvalidBoundaries").Replace("{0}", ContentProvider.GetString("RealWorkingTime"));
                return;
            }

            task.DataSignature = 0;

            Guid inChargeUser = Guid.Empty;
            try
            {
                inChargeUser = new Guid(hdfInChargeUserId.Value);
            }
            catch (Exception exp)
            {
                Console.Write(exp);
            }
            task.InChargeUserId = inChargeUser;

            TaskDAO dao = new TaskDAO();
            int result = dao.update(task);
            if (result > 0)
            {
                Util.CloseDialog(Response);
            }
            else
            {
                lblError.Text = ContentProvider.GetMessage("UnsuccessfullyUpdated");
            }
        }

        protected void ddlDepartment_SelectedIndexChanged(object sender, EventArgs e)
        {
            try
            {
                Guid deptId = new Guid(ddlDepartment.SelectedValue);
                List<BLRole> roles = new List<BLRole>();
                BLRole filter = new BLRole();
                filter.Id = Guid.Empty;
                filter.Name = string.Empty;
                filter.Department = new BLDepartment();
                filter.Department.Id = deptId;
                if (!deptId.Equals(Guid.Empty))
                {
                    RoleDAO roleDao = new RoleDAO();
                    roles = roleDao.searchRolesInDepartment(filter);
                }
                roles.Insert(0, filter);
                ddlRole.DataSource = roles;
                ddlRole.DataBind();

                loadUsers();
            }
            catch (Exception exp)
            {
                Console.Write(exp.StackTrace);
            }
        }

        private void loadUsers()
        {
            try
            {
                string roleName = ddlRole.SelectedItem.Text;
                List<BLUser> users = new List<BLUser>();
                if (!string.IsNullOrEmpty(roleName))
                {
                    string[] usernames = Roles.GetUsersInRole(roleName);
                    foreach (string un in usernames)
                    {
                        BLUser user = new BLUser(Membership.GetUser(un));
                        users.Add(user);
                    }
                }
                ddlUser.DataSource = users;
                ddlUser.DataBind();
                hdfInChargeUserId.Value = ddlUser.SelectedItem.Value;
            }
            catch (Exception exp)
            {
                Console.Write(exp.StackTrace);
            }
        }

        protected void ddlRole_SelectedIndexChanged(object sender, EventArgs e)
        {
            loadUsers();
        }

        protected void ddlUser_SelectedIndexChanged(object sender, EventArgs e)
        {
            hdfInChargeUserId.Value = ddlUser.SelectedItem.Value;
            lblInChargeAgent.Text = ddlUser.SelectedItem.Text;
        }
    }
}
